package cn.uway.controller;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import cn.uway.utils.WebUtils;


@ControllerAdvice
public class GlobalExceptionHandler{

	protected  Logger logger = LoggerFactory.getLogger(this.getClass());	
	
	private Pattern CN_PATTERN = Pattern.compile("^[\u4e00-\u9fa5]{1}$"); 

	 @ExceptionHandler(value = Throwable.class)
     public ModelAndView  defaultErrorHandler(HttpServletRequest request, HttpServletResponse response, Throwable e) throws Exception {
        logger.error("拦截到控制器异常", e);
        String errorMsg = e.getMessage();
        if(WebUtils.isEmpty(errorMsg)){
        	errorMsg = "系统错误，请联系管理员";
        }
        else{
        	Matcher m = CN_PATTERN.matcher(errorMsg.substring(0,1));
        	if(!m.matches()){ //非中文错误，则替换为默认的提示
        		errorMsg = "系统错误，请联系管理员";
        	}
        }        
        if(WebUtils.isAjax(request)){
        	String json = "{\"RET_CODE\":\"FAILED\", \"RET_MSG\":\"" +errorMsg+"\"}";
        	WebUtils.writeToPage(json ,  response);
        	return null;
        }
        else{
        	request.setAttribute("errorMsg", errorMsg);
        	return new ModelAndView ("/error"); 
        }
        
    }

    
}
